//
// Created by hsj on 2024-1-5.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>

#ifdef WIN32
//windows minGW64
//inet_ntop函数：_WIN32_WINNT
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <ws2tcpip.h>
//#pragma comment(lib,"ws2_32.lib")
#else
//linux  gcc
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#endif
#define BUF_SIZE 30
void error_handling(char *message);
int main(int argc, char *argv[]){
    int sd;
    FILE *fp;
    char buf[BUF_SIZE];
    int read_cnt;
    struct sockaddr_in serv_adr;
    char ip[]="127.0.0.1";
    char port[]="9999";

    fp=fopen("receive.dat", "wb" );
    sd=socket(PF_INET, SOCK_STREAM, 0);

    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family=AF_INET;
    serv_adr.sin_addr.s_addr=inet_addr(/*argv[1]*/ip);
    serv_adr.sin_port=htons(atoi(/*argv[2]*/port));

    connect(sd, (struct sockaddr* )&serv_adr, sizeof(serv_adr));

    // read函数是负责从fd中读取内容.当读成功时，read返回实际所读的字节数，
    // 如果返回的值是0表示已经读到文件的结束了，小于0表示出现了错误。
    // 如果错误为EINTR说明读是由中断引起的，如果是ECONNREST表示网络连接出了问题。
    while((read_cnt=read(sd, buf, BUF_SIZE ))!=0)
        fwrite((void*)buf, 1, read_cnt, fp);

    puts("Received file data --> receive.dat");
    char pc[] = "Thank you";
    write(sd, pc, sizeof(pc));

    fclose(fp);
    close(sd);

    return EXIT_SUCCESS;
}
void error_handling( char *message){
    fputs (message, stderr);
    fputc('\n', stderr);
    exit(1);
}